package com.oocl.im.server;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.oocl.im.gui.ErrorFrame;
import com.oocl.im.packet.MsgPackage;
import com.oocl.im.packet.Operation;

public class Server {
	private HashMap<String, ServerSocketThread> userThread = new HashMap<>();
	private HashMap<String, Boolean> userOn = new HashMap<>();

	public void start() throws Exception {
		ServerSocket server = new ServerSocket(8123);
		userOn.put("all", true);
		while (true) {
			Socket socket = server.accept();
			ObjectInputStream in = new ObjectInputStream(
					socket.getInputStream());
			ObjectOutputStream out = new ObjectOutputStream(
					socket.getOutputStream());
			MsgPackage msg = (MsgPackage) in.readObject();
			String sender = msg.getSender();
			boolean hasLogin = false;
			if (userOn.containsKey(sender)) {
				hasLogin = userOn.get(sender);
			}
			if (msg.getOpeartion() == Operation.LOGIN) {
				System.out.println(msg);
				if (!hasLogin) {
					String name = msg.getSender();
					System.out.println(name + " login");
					userOn.put(name, true);
					ServerSocketThread thread = new ServerSocketThread(name,
							socket, in, out, userThread, userOn);
					userThread.put(name, thread);
					new Thread(thread).start();
				} else {
					MsgPackage msgPackage = new MsgPackage(Operation.EXIT,
							null, null, "you has login ", null, null);
					out.writeObject(msgPackage);
					socket.close();
				}

			} else {
				MsgPackage msgPackage = new MsgPackage(Operation.EXIT, null,
						null, "you must login first", null, null);
				out.writeObject(msgPackage);
				socket.close();
			}
		}
	}

	public static void main(String[] args) throws Exception {
		new Server().start();
	}

}
